import 'package:flutter/material.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/api/download_manager.dart';
import 'package:loxen/api/http_util.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/utils/color.dart';
import 'package:loxen/utils/file_util.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class AppUpGrade {
  static void upGrade(BuildContext context) {
    bool isAndroid = Theme.of(context).platform == TargetPlatform.android;
    ApiService.upGradeApp(isAndroid).listen((event) async {
      String title;
      List<String> messages = [];
      if (isAndroid) {
        PackageInfo info = await PackageInfo.fromPlatform();
        int currentCode = int.parse(info.buildNumber);
        var dir = await FileUtil.getPath();
        FileUtil.deleteFile("${dir.path}/${info.version}.apk");
        int code = event.data['data']['code'];
        if (code != null) {
          if (code > currentCode) {
            title = '新版本：${event.data['data']['version_code']}';
            String url = event.data['data']['apk_url'];
            var list = event.data['data']['describe'];
            for (var data in list) {
              messages.add(data['describe']);
            }
            _showMessage(
                context, url, '${event.data['data']['version_code']}.apk', title, messages);
          }
        }
      } else {
        //TODO IOS更新
      }
    }, onError: (error, stack) {});
  }

  static void _showMessage(BuildContext buildContext, String url, String fileName, String title,
      List<String> messages) async {
    var data = await showDialog(
      context: buildContext,
      builder: (context) => upgradeDialog(
        title,
        messages,
        onNext: () => Navigator.pop(context),
        upgrade: () => Navigator.pop(context, true),
      ),
    );
    if (data != null && data) {
      _showDownloadDialog(buildContext, url, fileName);
    }
  }

  static _showDownloadDialog(BuildContext buildContext, String url, String fileName) {
    showDialog(
        context: buildContext,
        barrierDismissible: false,
        builder: (context) {
          ValueNotifier<double> progress = ValueNotifier(0);
          _installApk(context, url, fileName, onReceiveProgress: (count, total) {
            var value = count / total;
            if (value < 0.99) {
              progress.value = value;
            }
          }, done: (savePath) async {
            Navigator.pop(context);
            var result =
                await OpenFile.open(savePath, type: 'application/vnd.android.package-archive');
            print("type=${result.type}  message=${result.message}");
          }, failed: (e) {
            Navigator.pop(context);
            showDialog(
                context: buildContext,
                builder: (context) {
                  return _downloadFailDialog(cancel: () {
                    Navigator.pop(context);
                  }, retry: () {
                    Navigator.pop(context);
                    _showDownloadDialog(buildContext, url, fileName);
                  });
                });
          });
          return WillPopScope(onWillPop: () async => false, child: progressDialog(progress));
        });
  }

  //下载失败弹窗
  static AlertDialog _downloadFailDialog({Function() cancel, Function() retry}) {
    return AlertDialog(
        title: Text(
          '下载失败',
          style: TextStyle(
            color: Colors.black,
          ),
        ),
        actions: <Widget>[
          FlatButton(
            child: Text("取消"),
            onPressed: cancel,
          ),
          FlatButton(
            child: Text("重试"),
            onPressed: retry,
          ),
        ]);
  }

  //更新应用弹窗
  static AlertDialog upgradeDialog(String title, List<String> messages,
      {Function() onNext, Function() upgrade}) {
    List<Widget> list = [];
    for (int i = 0; i < messages.length; i++) {
      list.add(Text(
        "${i + 1}：${messages[i]}",
        style: TextStyle(
          color: Colors.black,
        ),
      ));
    }
    return AlertDialog(
        title: Text(
          title,
          style: TextStyle(
            color: Colors.black,
          ),
        ),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: list,
        ),
        actions: <Widget>[
          FlatButton(
            child: Text("下次提醒"),
            onPressed: onNext,
          ),
          FlatButton(
            child: Text("立即更新"),
            onPressed: upgrade,
          ),
        ]);
  }

  //进度条弹窗
  static AlertDialog progressDialog(ValueNotifier<double> progress) {
    return AlertDialog(
      title: Text('下载更新'),
      content: ValueListenableProvider.value(
        value: progress,
        builder: (context, _) {
          double value = context.watch<double>();
          String text = (value * 100).toStringAsFixed(0) + '%';
          if (text.length > 3) {
            text = '99%';
          }
          return Row(
            children: [
              Expanded(
                child: LinearProgressIndicator(
                  value: value,
                  minHeight: 24.h,
                  backgroundColor: Colors.white,
                  valueColor: AlwaysStoppedAnimation<Color>(Colours.app_main),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 10.w),
                child: Text(
                  text,
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: Colours.main_text,
                  ),
                ),
              )
            ],
          );
        },
      ),
    );
  }

  static void _installApk(
    BuildContext context,
    String url,
    String fileName, {
    Function(int count, int total) onReceiveProgress,
    Function failed,
    Function done,
  }) async {
    var dir = await FileUtil.getPath();
    if (dir != null) {
      String savePath = '${dir.path}/$fileName';
      await DownLoadManage().download(url, savePath,
          onReceiveProgress: onReceiveProgress, done: done, failed: failed);
    } else {
      Toast.show('缺少权限，更新失败！', context);
    }
  }
}
